package com.campusnews.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campusnews.annotation.LoginToken;
import com.campusnews.pojo.Admin;
import com.campusnews.pojo.Thing;
import com.campusnews.service.AdminService;
import com.campusnews.service.TokenService;
import com.campusnews.utils.EntryToMapUtils;
import com.campusnews.utils.JsonResult;
import com.campusnews.utils.TokenUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lqc
 * @since 2021-09-30
 */
@RestController
@ApiOperation(value = "管理员API", notes = "管理员API")
@RequestMapping("/admin")
@Api(tags={"管理员API"})
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private TokenService tokenService;

    // 登录
    @ApiOperation(value = "登陆", notes = "登陆")
    @RequestMapping(value = "/login" ,method = RequestMethod.POST)
    @ResponseBody
    public JsonResult adminLogin(@RequestParam("adminName") String adminName,
                                 @RequestParam("password") String password,
                                 HttpServletResponse response){
        JSONObject jsonObject = new JSONObject();
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("admin_name",adminName)
                .eq("password", password);
        Admin adminForBase= adminService.getOne(wrapper);
        if (adminForBase!=null) {
            String token = tokenService.getToken(adminForBase);
            jsonObject.put("token", token);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            return JsonResult.build(200,"登录成功",jsonObject);
        } else {
            return JsonResult.errorMsg("登录失败,用户名，密码错误");

        }
    }

//    /***
//     * 这个请求需要验证token才能访问
//     * @return String 返回类型
//     */
//    @LoginToken
//    @ApiOperation(value = "测试获取信息", notes = "测试获取信息")
//    @RequestMapping(value = "/getMessage" ,method = RequestMethod.GET)
//    public String getMessage() {
//        // 取出token中带的用户id 进行操作
//        System.out.println(TokenUtils.getTokenAdminId());
//        return "您已通过验证";
//    }

    @LoginToken
    @ApiOperation(value = "添加管理员信息", notes = "添加管理员信息")
    @RequestMapping(value = "/insertAdmin" ,method = RequestMethod.POST)
    public JsonResult insertAdmin(@RequestBody Admin admin) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("admin_name",admin.getAdminName());
        Admin adminForGet= adminService.getOne(wrapper);
        if (adminForGet!=null){
            return JsonResult.errorMsg("用户名已存在");
        }else {
            boolean save = adminService.save(admin);
            if (save){
                System.out.println(admin);
                return JsonResult.build(200,"管理员添加成功",save);
            }else {
                return JsonResult.errorMsg("管理员添加失败");
            }
        }
    }

    @LoginToken
    @ApiOperation(value = "修改管理员信息", notes = "修改管理员信息")
    @RequestMapping(value = "/updateAdmin" ,method = RequestMethod.POST)
    public JsonResult updateAdmin(@RequestBody Admin admin) {
        boolean update = adminService.saveOrUpdate(admin);
        if (update){
            return JsonResult.build(200,"管理员修改成功",update);
        }else {
            return JsonResult.errorMsg("管理员修改失败");
        }
    }

    @LoginToken
    @ApiOperation(value = "删除管理员信息", notes = "删除管理员信息")
    @RequestMapping(value = "/deleteAdmin/{adminId}" ,method = RequestMethod.GET)
    public JsonResult deleteAdmin(@PathVariable("adminId") int adminId) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("admin_id",adminId);
        boolean remove = adminService.remove(wrapper);
        if (remove){
            return JsonResult.build(200,"管理员删除成功",remove);
        }else {
            return JsonResult.errorMsg("管理员删除失败");
        }
    }

    @LoginToken
    @ApiOperation(value = "分页精确查询管理员信息", notes = "分页精确管理员信息")
    @RequestMapping(value = "/selectAdminByAccurate" ,method = RequestMethod.POST)
    public JsonResult selectAdminByAccurate(@RequestBody Admin admin) {
        Map<String, Object> map = new HashMap<>();
        try {
            map = EntryToMapUtils.entryToMap(admin);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //条件查询器
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.allEq(map);
        if (!(admin.getSortOrder()==null||admin.getSortOrder().length()==0)){
            wrapper.orderByDesc(admin.getSortOrder());
        }
        PageHelper.startPage(admin.getPage(),admin.getPageSize());
        PageInfo<Admin> pageInfo = new PageInfo<>((Page<Admin>)adminService.list(wrapper));
        System.out.println(pageInfo);
        return JsonResult.build(200,"分页精确查询成功",pageInfo);
    }

    @LoginToken
    @ApiOperation(value = "分页模糊查询管理员信息", notes = "分页模糊管理员信息")
    @RequestMapping(value = "/selectAdminByVague" ,method = RequestMethod.POST)
    public JsonResult selectAdminByVague(@RequestBody Thing things) {
        //条件查询器
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        String thing = things.getThing();
        if (!(thing==null||thing.length()==0)){
            wrapper.like("admin_name",thing).or()
                    .like("password",thing).or()
                    .like("signature",thing).or();
        }
        if (!(things.getSortOrder()==null||things.getSortOrder().length()==0)){
            wrapper.orderByDesc(things.getSortOrder());
        }
        PageHelper.startPage(things.getPage(),things.getPageSize());
        PageInfo<Admin> pageInfo = new PageInfo<>((Page<Admin>)adminService.list(wrapper));
        System.out.println(pageInfo);
        return JsonResult.build(200,"分页模糊查询成功",pageInfo);
    }
}

